import { Component, OnInit, ViewChildren, QueryList, ElementRef, ViewChild } from '@angular/core';
import { Router } from '@angular/router';
import * as pinyin from 'pinyin';
import { HttpService } from '../service/http.service';

interface SortItem {
  letter: string;
  data: Array<any>;
}

@Component({
  selector: 'app-address-book',
  templateUrl: './address-book.page.html',
  styleUrls: ['./address-book.page.scss'],
})
export class AddressBookPage implements OnInit {

  friends: Array<SortItem> = []

  @ViewChild('top')
  topElement: ElementRef;

  @ViewChildren('contacts')
  contactElements: QueryList<ElementRef>;

  constructor(private router: Router, private httpService: HttpService) {
    for (var i = 0; i < 26; i++) {
      this.friends.push({ letter: String.fromCharCode(65 + i), data: [] })
    }
    this.friends.push({ letter: '#', data: [] })
  }

  ngOnInit() {
    this.httpService.getFriends().then(result => {
      result.data.forEach(item => {
        const letters = pinyin(item.remarkName.charAt(0), { style: pinyin.STYLE_FIRST_LETTER })
        if (letters && letters[0] && letters[0][0]) {
          const letter = letters[0][0].charAt(0).toUpperCase()
          const index = letter.charCodeAt() - 65
          this.friends[index].data.push(item)
        } else {
          this.friends[26].data.push(item)
        }
      })
      console.log(this.friends)
    })
  }

  scollTo(index: any) {
    if (index == 'top') {
      this.topElement.nativeElement.scrollIntoView()
      return
    }
    this.contactElements.get(index).nativeElement.scrollIntoView()
  }

  showFriendDetail(friend) {
    this.router.navigate(['/contacts/contacts-detail'], { queryParams: { friendId: friend.id } })
  }
}
